﻿using System;
using FrameDesign.FrameWork;
using FrameDesign.FrameWork.Rule;
using FrameDesign.FrameWork.Singleton;
using FrameworkDesign;
using FrameWorkDesign.Example.Event;
using UnityEngine;
using UnityEngine.UI;

namespace FrameDesign.Example2.Scripts
{
    public class CounterViewController : MonoBehaviour, IController
    {
        private ICounterModel mCounterModel;
        void Start()
        {
            // 获取
            mCounterModel = GetArchitecture().GetModel<ICounterModel>();

            // 注册
            mCounterModel.Count.RegisterOnValueChanged(OnCountChanged);

            transform.Find("BtnAdd").GetComponent<Button>()
                .onClick.AddListener(this.SendCommand<AddCountCommand>);

            transform.Find("BtnSub").GetComponent<Button>()
                .onClick.AddListener(this.SendCommand<SubCountCommand>);

            OnCountChanged(mCounterModel.Count.Value);
        }

        // 表现逻辑
        private void OnCountChanged(int newValue)
        {
            transform.Find("CountText").GetComponent<Text>().text = newValue.ToString();
        }

        private void OnDestroy()
        {
            // 注销
            mCounterModel.Count.UnRegisterOnValueChanged(OnCountChanged);

            mCounterModel = null;
        }
        public IArchitecture GetArchitecture() // 修改
        {
            return CounterApp.Interface;
        }
    }
    public interface ICounterModel : IModel
    {
        BindableProperty<int> Count { get; }
    }
    /// <summary>
    /// 不需要是单例了
    /// </summary>
    public class CounterModel : AbstractModel, ICounterModel
    {
        protected override void OnInit() // 修改 Init -> OnInit
        {
            // 通过 Architrecture 获取
            var storage = this.GetUtility<IStorage>(); // 通过 this 调用
            
            Count.Value = storage.LoadInt("COUNTER_COUNT", 0);

            Count.RegisterOnValueChanged(count =>
            {
                storage.SaveInt("COUNTER_COUNT", count);
            });
        }

        public BindableProperty<int> Count { get; } = new BindableProperty<int>()
        {
            Value = 0
        };
    }

}